<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证器</title>
</head>

<body>
    <div id="app">
        <!-- 不能超过四个字 -->
        <input v-valid.len="{len:4,fn,bn}" type="text" v-model="username">
        <br>
        <input v-valid.phone="{fn,bn}" type="text" v-model="phone">
        <br>
        <!-- <input v-valid.email type="text" v-model="username">
        <br>
        <input v-valid.regex="{preg:/.*/}" type="text" v-model="username">
        <br> -->
        <button :disabled="btn">添加用户</button>
    </div>
    <script src="/vue.js"></script>
    <script>
        Vue.directive('valid', (el, binds) => {
        
            //    通过修饰符鉴别
            const modifiers = binds.modifiers

            if (modifiers.len) {
                // 字符串长度限制
                let len = binds.value.len || 6
                if (el.value.length > len) {
                    binds.value.fn()
                    el.style.color = 'red'
                   
                                 
                } else {
                    binds.value.bn()
                    el.style.color = ''
                   
                }
            }

            // 电话
            if (modifiers.phone) {
                let preg = /^1[3-9]\d{9}$/
                if (!preg.test(el.value)) {
                    binds.value.fn()
                    el.style.color = 'red'
                } else {
                    binds.value.bn()
                    el.style.color = ''
                }

         }
           

        })


        const app = new Vue({
            el: "#app",
            data: {
                btn: false,
                username: '',
                msg: "请填写用户名",
                phone: ''
            },
            methods: {
                fn() {
                    this.btn = true;
                },
                bn() {
                    this.btn = false
                }
            }
        })



    </script>
</body>

</html>